package com.apache.client.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apache.api.api.IBaseLoginUser;
import com.apache.api.vo.ResultEntity;
import com.apache.oscache.OsCacheManager;
import com.apache.passport.common.PassportHelper;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.ToolsUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: Hou Dayu
 * @date: Created in 2021/2/8
 */
public class DefLoginUserImpl implements IBaseLoginUser {

    @Override
    public Object findLoginUser(String tokenId, HttpServletRequest request, HttpServletResponse response) {
        if(StrUtil.isNotNull(tokenId)){
            LoginUser loginUser = (LoginUser) OsCacheManager.getInstance().getLoginUser(tokenId);
            if(null == loginUser){
                loginUser = setLoginUser(request, tokenId);
            }
            return loginUser;
        }
        return null;
    }

    /**
     * 获取当前登录用户信息
     */
    private LoginUser setLoginUser(HttpServletRequest request, String tokenId) {
        Map params = new HashMap();
        String useEname = StrUtil.doNull(PassportHelper.getInstance().getCurrCookie(request, "_uc.sso"),request.getHeader("zuulucsso"));
        if(StrUtil.isNotNull(useEname)) {
            params.put("userEname", useEname);
        }
        params.put("token", tokenId);
        params.put("sysPass", ConfigUtil.getInstance().interfacePass());
        ResultEntity entity = LoadRpcService.service().doService("uctService","loginUserInfoSso","xml",params,null);
        if ("true".equals(entity.getResult()) && null != entity.getEntity()) {
            LoginUser loginUser = (LoginUser) entity.getEntity();
            OsCacheManager.getInstance().putLoginUser(tokenId, loginUser);
            params.put("userEname",loginUser.getUserEname());
            request.getSession().setAttribute("sysUser", loginUser.getSysFlag());
            entity = LoadRpcService.service().doService("uctService","roleList","xml",params,null);
            if ("true".equals(entity.getResult()) && null != entity.getEntity()) {
                List roles = (List) entity.getEntity();
                OsCacheManager.getInstance().putCustomerUser(loginUser.getUser().getUserId(), roles);
                request.getSession().setAttribute("loginUserRoles", roles);
            }
            return loginUser;
        }
        return null;
    }
}
